const fs = require('fs')
const path = require('path')
const got = require('got')
const imageType = require('image-type')
const randomString = require('randomstring')
const { Menu, dialog, app, ipcMain } = require('electron')

let event = null

ipcMain.on('on-watch-download-event', (e, args) => {
    event = e
})

const saveImg = (src, win) => {
    if (src) {
        const contextMenu = Menu.buildFromTemplate([
            {
                label: '图片另存为...',
                accelerator: 'Ctrl+Shift+S',//定义快捷键
                click: () => {
                    got.get(src).then(async (res) => {
                        const chunk = Buffer.from(res.rawBody)
                        const { ext } = imageType(chunk)
                        const fileName = `${randomString.generate(10)}.${ext}`
                        const { filePath, canceled } = await dialog.showSaveDialog({
                            title: '图片另存为',
                            defaultPath: path.resolve(__dirname, `${app.getPath('downloads')}/${fileName}`)
                        })
                        if (!canceled) {
                            fs.writeFileSync(filePath, chunk)
                            event && event.sender.send('on-download-event', { filePath, chunk })
                        }
                    }).catch(err => {
                        dialog.showErrorBox('不支持的图片格式', '')
                    })
                }
            }
        ])
        contextMenu.popup()
    }
}

module.exports = saveImg